const mysql = require("mysql");
const mysqlConfig: any = require("./config.ts");

export const pool: any = mysql.createPool(mysqlConfig);

// 检测数据库是否连接成功
// db.query("select 1", (err, results) => {
//   if (err) return console.log(err);
//   console.log(results);
// }

/**
 * 执行查询并返回结果
 * @param {string} sql - SQL查询语句
 * @param {any[]} [params] - SQL查询参数
 * @returns {Promise<any[]>} - 查询结果数组
 */
export const query = (sql: string, params: any[] = []): Promise<any []> => {
  return new Promise((resolve, reject) => {
    pool.query(sql, params, (err: Error, rows: any) => {
      if (err) {
        reject(err);
      } else {
        resolve(rows);
      }
    });
  });
};

/**
 * 插入数据
 * @param {string} table - 数据表名
 * @param {object} data - 要插入的数据对象
 * @param {string[]} [keys] - 数据对象的键数组
 * @returns {Promise<any>} - 插入操作的结果
 */
export const insert = (
  table: string,
  data: Object,
  keys = Object.keys(data)
) => {
  const sql = `INSERT INTO ${table} (${keys.join(",")}) VALUES (?)`;
  return query(sql, [Object.values(data)]);
};

/**
 * 更新数据
 * @param {string} table - 数据表名
 * @param {object} data - 要更新的数据对象
 * @param {object} condition - 更新条件
 * @returns {Promise<any>} - 更新操作的结果
 */
export const update = (table: string, data: Object, condition: Object) => {
  const setClauses = Object.entries(data).map(([key, value]) => `${key} = ?`);
  const sql = `UPDATE ${table} SET ${setClauses.join(",")} WHERE ${Object.keys(
    condition
  )
    .map((key) => `${key} = ?`)
    .join(" AND ")}`;
  const values = Object.values(data).concat(Object.values(condition));
  return query(sql, values);
};

/**
 * 删除数据
 * @param {string} table - 数据表名
 * @param {object} condition - 删除条件
 * @returns {Promise<any>} - 删除操作的结果
 */
export const del = (table: string, condition: any) => {
  const sql = `DELETE FROM ${table} WHERE ${Object.keys(condition)
    .map((key) => `${key} = ?`)
    .join(" AND ")}`;
  const values = Object.values(condition);
  return query(sql, values);
};
